<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CommentController extends Controller
{
    /*评论列表*/
    public function getIndex() {
        $date = DB::table('comment') -> join('home_user','comment.uid','=','home_user.h_uid') -> join('goods','comment.gid','=','goods.gid') -> get();
        return view('admin/comment/index',['date'=>$date]);
    }

    /*删除评论*/
    public function getDelete(Request $request) {
        $this -> validate($request,[
            'id' => 'required'
        ],[
            'id.required' => '需要输入评论的id'
        ]);

        $id = $request -> input('id');
        $res = DB::table('comment') -> where('id',$id) -> delete();
        if($res > 0){
            return redirect('admin/comment/index') -> with('success','删除成功');
        }else{
            return back() -> with('error','删除失败');
        }
    }

    /*评论详情*/
    public function getDetail(Request $request) {
        $this -> validate($request,[
            'id' => 'required'
        ],[
            'id.required' => '需要输入评论的id'
        ]);

        $id = $request -> input('id');
        $date = DB::table('comment') -> where('id',$id) -> join('home_user','comment.uid','=','home_user.h_uid') -> join('goods','comment.gid','=','goods.gid') -> first();
        return view('admin/comment/detail',['date'=>$date]);
    }

    /*查询评论,用于后台数据统计的好评度查询*/
    public function postPingjia(Request $request){
        // echo 'heheh';
        $gid = $request -> input('gid');
        $data = DB::table('goods') -> where('gid',$gid) -> select('gid','gpic','gname') -> first();
        if(empty($data)){
            echo json_encode(['err' => 9]);            
            return;
        }
        // 评论总数
        $com_count = DB::table('comment') -> where('gid',$gid) -> count();
        // 好评个数
        $com_count_hao = DB::table('comment') -> where('gid',$gid) -> where('eval',1) -> count();
        // 中评个数
        $com_count_zhong = DB::table('comment') -> where('gid',$gid) -> where('eval',2) -> count();
        // 差评个数
        $com_count_cha = DB::table('comment') -> where('gid',$gid) -> where('eval',3) -> count();
        // 如果总数为0 则好评率为0
        if($com_count == 0){
            $data['hao'] = 0;
            $data['zhong'] = 0;
            $data['cha'] = 0;
        }else{
            // 如果总数不为0,进行正常计算
            $data['hao'] = round($com_count_hao/$com_count,4)*100;
            $data['zhong'] = round($com_count_zhong/$com_count,4)*100;
            $data['cha'] = round($com_count_cha/$com_count,4)*100;
        }        

        $data = json_encode($data);
        echo $data;
    }

}
